<script setup>
import { ref, reactive, computed, toRaw } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import UQRCode from 'uqrcodejs';
// 创建app实例
const app = getApp();
// 页面服务详情信息
const service = ref({});
// 医院的数据源
const hospitalList = ref([]);
// 医院的索引
const hospitalIndex = ref(0);
// 订单详情
const order = reactive({
	price: '',
	starttime: '',
	address: {
		userName: '',
		cityName: '',
		countryName: '',
		detailInfo: ''
	},
	receiveAddress: '',
	tel: '',
	demand: ''
});
// 陪诊人信息
const client = reactive({
	name: ''
});
// 判断是否同意协议
const is_xieyi = ref(false);
const cfg = reactive({
	page_xy: '',
	page_fw: ''
});
// 表单提交弹框显示按钮
const popup = ref();
// 手机验证信息
const validMobile = reactive({
	phone: '',
	validCode: ''
});
// 手机验证
const countdown = reactive({
	validText: '获取验证码',
	time: 60
});
// 弹出支付界面
const qrcodePopup = ref();
// 监听页面加载时
onLoad((options) => {
	console.log('服务页面加载时接受数据', options);
	recommendGo(options);
});
// 当页面加载时，获取点击的id并根据id请求数据，并跳转到订单页
const recommendGo = (options) => {
	app.globalData.utils.request({
		url: '/Service/order',
		data: {
			svid: options.svid
		},
		success: (res) => {
			// console.log('res总信息', res);
			service.value = res.data.service;
			hospitalList.value = res.data.hospitals;
			// 默认选中
			const hospitalData = toRaw(hospitalList.value);
			console.log('hospdata', hospitalData);
			if (options.hid > 0) {
				// 自动选中
				for (let i = 0; i < hospitalData.length; i++) {
					if (hospitalData[i].id == options.hid) {
						hospitalIndex.value = i;
						order.price = hospitalData[i].service_price;
						break;
					}
				}
			}
			console.log('服务信息', service.value);
		}
	});
};
// 点击服务内容，显示弹框按钮
const handleTap = () => {};
// 改变医院的数据
const onHospitalChange = (e) => {
	const value = parseInt(e.detail.value);
	hospitalIndex.value = value;
	order.price = toRaw(hospitalList.value)[value].service_price;
};
// 修改日期组件
const onStartTimeChanged = (e) => {
	order.starttime = e.detail.value;
};
// 选择就诊对象
const onClientChange = () => {
	uni.navigateTo({
		url: '../clients/index?act=select'
	});
};

// 创建监听全局的自定义事件，用来获取其他组件的数据
uni.$on('clientChange', (data) => {
	// console.log(111, data);
	client.name = data.name;
	client.id = data.user_id;
	client.sex = data.sex;
	client.age = data.age;
	client.mobile = data.mobile;
});
// 创建点击勾选按钮事件
const onXieyiChange = () => {
	is_xieyi.value = !is_xieyi.value;
};
// 点击获取地址
const onAddressChange = () => {
	uni.chooseAddress({
		success: (res) => {
			console.log('获取的用户地址', res);
			order.address.userName = res.userName;
			order.address.cityName = res.cityName;
			order.address.countryName = res.countyName;
			order.address.detailInfo = res.detailInfo;
		},
		fail: (err) => {
			console.log(err);
		}
	});
};
// 表单数据的全局使用
let submitData;
// 提交表单检测
const submit = () => {
	// 判断是否统一协议
	if (!is_xieyi.value) {
		return uni.showToast({
			title: '请先阅读并同意服务协议',
			icon: 'none',
			duration: 1000
		});
	}
	const orderData = toRaw(order);
	const serviceData = toRaw(service.value);
	const hospitalData = toRaw(hospitalList.value);
	const clientData = toRaw(client);
	orderData.service_code = serviceData.code;
	orderData.service_id = serviceData.id;
	orderData.service_name = serviceData.name;
	orderData.service_stype = serviceData.stype;
	// console.log('服务对象的信息', clientData);
	// 公共信息的校验
	if (serviceData.stype < 100) {
		if (hospitalIndex.value === 0) {
			return uni.showToast({
				title: '请选择医院',
				icon: 'none',
				duration: 1000
			});
		}
	}
	orderData.hospital_id = hospitalData[hospitalIndex.value].id;
	orderData.hospital_name = hospitalData[hospitalIndex.value].name;
	// 就诊时间的校验
	if (!orderData.starttime) {
		return uni.showToast({
			title: '请选择就诊时间',
			icon: 'none',
			duration: 1000
		});
	}
	// 服务类型为陪诊
	if (serviceData.stype == 10 || serviceData.stype == 15 || serviceData.stype == 20) {
		// 对就诊人进行校验
		if (!clientData.id) {
			return uni.showToast({
				title: '请选择就诊人',
				icon: 'none',
				duration: 1000
			});
		}
		(orderData.client = {}),
			(orderData.client.age = clientData.age),
			(orderData.client.mobile = clientData.mobile),
			(orderData.client.name = clientData.name),
			(orderData.client.sex = clientData.sex);
		// 接送地址验证
		if (serviceData.stype == 15) {
			if (!orderData.receiveAddress) {
				return uni.showToast({
					title: '请选择就诊人所在地址',
					icon: 'none',
					duration: 1000
				});
			}
		}
	}
	if (serviceData.stype == 30 || serviceData.stype == 40) {
		// 收件地址
		if (!orderData.address.userName) {
			return uni.showToast({
				title: '请选择收件信息',
				icon: 'none',
				duration: 1000
			});
		}
	}
	// 判断联系电话
	if (!orderData.tel) {
		return uni.showToast({
			title: '请填写你的联系方式',
			icon: 'none',
			duration: 1000
		});
	}
	submitData = orderData;
	// 判断当前用户是否存在
	if (!uni.getStorageSync('token')) {
		popup.value.open('center');
	} else {
		// 进行下单

		createOrder(submitData);
	}
};
// 提交表单的确认和取消
const ok = () => {
	// 点击确定，加盐手机号和验证码
	if (!(validMobile.phone || validMobile.validCode)) {
		return uni.showToast({
			title: '请输入正确的手机号或验证码',
			icon: 'none',
			duration: 1000
		});
	}
	console.log('用户输入的信息', validMobile.phone, validMobile.validCode),
		// 验证验证码
		app.globalData.utils.request({
			url: '/user/authentication',
			method: 'post',
			data: {
				tel: validMobile.phone,
				code: validMobile.validCode
			},

			success: (res) => {
				// 将token信息缓存
				uni.setStorageSync('token', res.data.token);
				// 下单的方法
				createOrder(submitData);
			},
			fail: (err) => {
				console.log('响应失败的结果', err);
				return uni.showToast({
					title: err.data.msg,
					icon: 'none',
					duration: 1000
				});
			}
			// console.log('用户输入的信息',tel,code),
		});
};
const cancal = () => {
	// 点击取消，关闭弹窗
	popup.value.close();
};
// 验证码倒计时开始
let flag = false; // 代表是否点击获取验证码
const countdownChange = () => {
	// 判断手机号是否存在
	const regPhone = /^1[3-9]\d{9}$/;
	if (!regPhone.test(validMobile.phone)) {
		return uni.showToast({
			title: '请输入正确的手机号',
			icon: 'none',
			duration: 1000
		});
	}
	if (!validMobile.phone) {
		return uni.showToast({
			title: '请输入手机号',
			icon: 'none',
			duration: 1000
		});
	}
	if (flag) return;
	const time = setInterval(() => {
		if (countdown.time <= 0) {
			countdown.validText = '获取验证码';
			countdown.time = 60;
			flag = false;
			clearInterval(time);
		} else {
			countdown.time -= 1;
			countdown.validText = `剩余${countdown.time}s`;
		}
	}, 1000);
	flag = true;
	// 发送验证码
	app.globalData.utils.request({
		url: '/get/code',
		method: 'post',
		data: {
			tel: validMobile.phone
		},
		success: (res) => {
			return uni.showToast({
				title: '验证码发送成功',
				icon: 'none',
				duration: 1000
			});
		},
		fail: (err) => {
			return uni.showToast({
				title: err.msg,
				icon: 'none',
				duration: 1000
			});
		}
	});
};
// 创建订单
const createOrder = (orderData) => {
	// 调用下单的接口
	app.globalData.utils.request({
		url: '/pay/createOrder',
		method: 'post',
		header: {
			token: uni.getStorageSync('token')
		},
		data: orderData,
		success: (res) => {
			console.log('创建订单成功', res);
			qrcodePopup.value.open('center');
			// 获取uQRCode实例
			const qr = new UQRCode();
			// 设置二维码内容
			qr.data = res.wx_code;
			// 设置二维码大小，必须与canvas设置的宽高一致
			qr.size = 150;
			// 调用制作二维码方法
			qr.make();
			// 获取canvas上下文
			var canvasContext = uni.createCanvasContext('qrcode'); // 如果是组件，this必须传入
			// 设置uQRCode实例的canvas上下文
			qr.canvasContext = canvasContext;
			// 调用绘制方法将二维码图案绘制到canvas上
			qr.drawCanvas();
		},
		fail: (err) => {
			console.log('创建订单失败', err);
		}
	});
};
// 跳转到订单列表
const payment = () => {
	uni.switchTab({
		url: '../order/index'
	});
};
</script>

<template>
	<view>
		<!-- 订单界面的进度条 -->
		<view class="od-banner">
			<image class="od-banner-icon" src="/static/resource/images/od_bg_icon.png" mode="widthFix" />
			<view class="od-jd od-jd-0">
				<view class="od-jd-out">
					<view class="od-jd-in"></view>
				</view>
				<view class="vp-flex od-jd-text">
					<view class="vp-flex_1">
						<text class="od-jd-st-0">填写订单</text>
					</view>
					<view class="vp-flex_1">
						<text class="od-jd-st-10">在线支付</text>
					</view>
					<view class="vp-flex_1">
						<text class="od-jd-st-20">专人服务</text>
					</view>
					<view class="vp-flex_1">
						<text class="od-jd-st-30">服务完成</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 公共盒子，用来接收页面服务内容信息 -->
		<view class="pub-box">
			<view class="pub-box-bd">
				<view class="weui-cell weui-cell_input">
					<view class="weui-cell__hd">
						<image class="serv-icon" :src="service.icon_image ? service.icon_image_url : '../../static/resource/images/avatar.jpg'"></image>
					</view>
					<view class="weui-cell__bd">
						<text class="serv-name">{{ service.name }}</text>
					</view>
					<view class="weui-cell__ft">
						<view class="f5 ic_info" @click="handleTap">服务内容</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 代跑取药： -->
		<block v-if="service.stype == 30 || service.stype == 40">
			<!-- 送取结果,代跑取药 -->
			<view class="pub-box">
				<view class="pub-box-bd">
					<!-- 选择就诊医院组件 -->
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">就诊医院：</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
								<picker @change="onHospitalChange" :value="hospitalIndex" :range="hospitalList" range-key="name">
									<input type="text" :disabled="true" placeholder="请选择就诊所在医院" :value="hospitalList[hospitalIndex].name" placeholder-class="vp-placeholder" />
								</picker>
							</view>
						</view>
					</view>
					<!-- 选择就诊时间组件 -->
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">服务时间：</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
								<dtPicker @dtPickerChanged="onStartTimeChanged" :timestamp="order.starttime" placeholder="请选择期望服务时间"></dtPicker>
							</view>
						</view>
					</view>
					<!-- 选择就诊人员组件 
					<view class="weui-cell weui-cell_input" @click="onClientChange">
						<view class="weui-cell__hd">就诊人</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<input class="weui-input" :disabled="true" style="text-align: right" placeholder-class="vp-placeholder" placeholder="请选择就诊对象" :value="client.name" />
						</view>
					</view>
					 就诊地址
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">服务地址</view>
						<view class="weui-cell__bd">
							<input
								class="weui-input"
								name="receiveAddress"
								style="text-align: right"
								placeholder-class="vp-placeholder"
								placeholder="请填写服务所在地址"
								v-model="order.receiveAddress"
							/>
						</view>
					</view> -->
					<!-- 收件信息 -->
					<view class="weui-cell weui-cell_input" @click="onAddressChange">
						<view class="weui-cell__hd">
							<view class="weui-label">收件信息：</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<input
								class="weui-input"
								:disabled="true"
								style="text-align: right; width: 460rpx"
								placeholder-class="vp-placeholder"
								placeholder="请选择收件信息"
								:value="order.address.userName ? order.address.userName + '(' + order.address.cityName + order.address.countyName + order.address.detailInfo + ')' : ''"
							/>
							<!-- {{order.address?(order.address.userName+'('+order.address.telNumber+')'):''}} -->
						</view>
					</view>
					<!-- 就诊人联系电话 -->
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">联系电话：</view>
						<view class="weui-cell__bd">
							<input
								class="weui-input"
								type="number"
								name="tel"
								style="text-align: right"
								placeholder-class="vp-placeholder"
								placeholder="请填写您的联系电话"
								v-model="order.tel"
							/>
						</view>
					</view>
				</view>
			</view>
		</block>
		<!-- 上门服务： -->
		<block v-if="service.stype == 10 || service.stype == 15 || service.stype == 20">
			<!-- 上门服务 -->
			<view class="pub-box">
				<view class="pub-box-bd">
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">服务时间：</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
								<dtPicker @dtPickerChanged="onStartTimeChanged" :timestamp="order.starttime" placeholder="请选择期望服务时间"></dtPicker>
							</view>
						</view>
					</view>

					<view class="weui-cell weui-cell_input" @click="onClientChange">
						<view class="weui-cell__hd">服务对象：</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<input class="weui-input" :disabled="true" style="text-align: right" placeholder-class="vp-placeholder" placeholder="请选择服务对象" :value="client.name" />
						</view>
					</view>
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">服务地址：</view>
						<view class="weui-cell__bd">
							<input
								class="weui-input"
								name="receiveAddress"
								style="text-align: right"
								placeholder-class="vp-placeholder"
								placeholder="请填写服务所在地址"
								v-model="order.receiveAddress"
							/>
						</view>
					</view>
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">联系电话：</view>
						<view class="weui-cell__bd">
							<input
								class="weui-input"
								type="number"
								name="tel"
								style="text-align: right"
								placeholder-class="vp-placeholder"
								placeholder="请填写您的联系电话"
								v-model="order.tel"
							/>
						</view>
					</view>
				</view>
			</view>
		</block>
		<!-- 服务需求备注清单 -->
		<view class="pub-box">
			<view class="pub-box-tt">服务需求</view>
			<view class="pub-box-bd">
				<view class="weui-cell weui-cell_input">
					<view class="weui-cell__bd">
						<textarea
							name="demand"
							auto-height
							placeholder="请简单描述您要就诊的科室.."
							placeholder-class="vp-placeholder"
							style="min-height: 150rpx; width: 100%"
							v-model="order.demand"
						/>
					</view>
				</view>
			</view>
		</view>
		<view style="height: 300rpx"></view>
		<!-- 悬浮提交按钮 -->
		<view class="vp-foot">
			<view style="background: #ffffff; padding: 20rpx">
				<view class="xieyi" style="text-align: center">
					<text :class="'is_xieyi ' + (is_xieyi ? 'is_xieyi_on' : '')" @click="onXieyiChange">我已阅读并同意</text>
					<navigator :url="cfg.page_xy">《用户协议》</navigator>
					<text>和</text>
					<navigator :url="cfg.page_fw">《服务协议》</navigator>
				</view>
				<view>
					<button :class="'btnp ' + (is_xieyi ? '' : 'btnp-disabled')" @click="submit">
						确认下单
						<block v-if="order.price > 0">（支付{{ order.price }}元）</block>
					</button>
				</view>
			</view>
		</view>
		<!-- 判断是否登录来显示验证用户信息 -->
		<uni-popup ref="popup" type="center" :is-mask-click="false" background-color="#fff">
			<view class="popup-content">
				<view class="group">
					<input class="uni-input" type="tel" v-model="validMobile.phone" placeholder="手机号" />
				</view>
				<view class="group">
					<input class="uni-input" v-model="validMobile.validCode" placeholder="验证码" />
					<text class="valid-text" @click="countdownChange">{{ countdown.validText }}</text>
				</view>
			</view>
			<view class="btns">
				<view class="cancal" @click="cancal">取消</view>
				<view class="ok" @click="ok">确定</view>
			</view>
		</uni-popup>
		<uni-popup ref="qrcodePopup" type="center" :is-mask-click="false" background-color="#fff">
			<view class="pay-box">
				<image @click="payment" src="../../static/resource/images/modal_closer.png" mode="" style="dispaly: block; width: 30rpx; height: 30rpx; margin-left: 300rpx"></image>
				<view class="text-center">微信支付</view>
				<canvas id="qrcode" canvas-id="qrcode" style="width: 300rpx; hieght: 300rpx"></canvas>
				<view class="text-center">请用本人微信扫描二维码</view>
			</view>
		</uni-popup>
	</view>
</template>

<style>
@import './index.css';
</style>
